package cn.anc.aonicardv.module.ui.album;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.AlbumBean;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.LocalDeleteEvent;
import cn.anc.aonicardv.event.LongClickEditEvent;
import cn.anc.aonicardv.event.PlayVideoDataEvent;
import cn.anc.aonicardv.module.adpter.album.UrgentVideoAdapter;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemClickListener;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemLongClickListener;
import cn.anc.aonicardv.module.ui.base.BaseFragment;
import cn.anc.aonicardv.net.download.DownLoadManager;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.AoniBeanDecorationUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.MediaScanner;
import cn.anc.aonicardv.util.ViewUtil;
import cn.anc.aonicardv.widget.AlbumDecoration;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.cache.CacheManager;

/**
 * Created by yangdai on 2017/5/18.
 */

public class UrgentFragment extends BaseFragment implements MediaScanner.ScanCompleteCallBack, MediaScannerConnection.OnScanCompletedListener, OnAlbumItemLongClickListener, OnAlbumItemClickListener {

    @BindView(R2.id.rv_urgent)
    RecyclerView urgentRv;

    @BindView(R2.id.iv_loading)
    ImageView loadingIv;
    private UrgentVideoAdapter videoAdapter;
    public List<VideoBean> videoBeanList;
    private List<AlbumBean> result;
    private Handler handler = new Handler();
    private List<VideoBean> deleteBeans = new ArrayList<>();
    private ProgressDialog progressDialog;
    public List<AlbumDecoration.DecorationBean> decorationBeanList;
    private AlbumDecoration decoration;
    private DialogUtils dialogUtils;
    private GridLayoutManager gridLayoutManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView(R.layout.fragment_urgent);
    }

    @Override
    public void initVariable() {
        videoAdapter = new UrgentVideoAdapter(this);
        dialogUtils = new DialogUtils();
        progressDialog = dialogUtils.getProgressDialog(getContext());
        gridLayoutManager = null;
    }
    private View mLayoutNoDataView;
    @Override
    public void findViewById(View view) {
        mLayoutNoDataView = view.findViewById(R.id.layout_no_data_view);
    }

    @Override
    public void setListener() {
        videoAdapter.setOnItemClickListener(this);
        videoAdapter.setOnItemLongClickListener(this);
    }

    @Override
    public void initData() {
        videoAdapter.registerEventBusForAdapter();
        updateUI();
    }
    private Handler mHandler = new Handler();
    @Override
    public void onResume() {
        super.onResume();

        if (videoBeanList == null || videoBeanList.isEmpty()) {
            ViewUtil.showContentLayout(Constant.LAYOUT_EMPTY, mLayoutNoDataView, urgentRv,R.mipmap.urgent_video_empty,getActivity().getResources().getString(R.string.urgent_video_empty_hint));

        } else {
            ViewUtil.showContentLayout(Constant.LAYOUT_DATA, mLayoutNoDataView, urgentRv);
        }
        videoAdapter.notifyDataSetChanged();
        setDecoration();
    }

    private void updateUI() {
        loadingIv.setVisibility(View.VISIBLE);
        if (videoBeanList != null && videoBeanList.isEmpty()) {
            loadingIv.setVisibility(View.INVISIBLE);
            ViewUtil.showContentLayout(Constant.LAYOUT_EMPTY, mLayoutNoDataView, urgentRv,R.mipmap.urgent_video_empty,getActivity().getResources().getString(R.string.urgent_video_empty_hint));

        } else if (videoBeanList != null && !videoBeanList.isEmpty()) {
            ViewUtil.showContentLayout(Constant.LAYOUT_DATA, mLayoutNoDataView, urgentRv);
            loadingIv.setVisibility(View.INVISIBLE);
        }
        videoAdapter.setData(videoBeanList);
        urgentRv.setAdapter(videoAdapter);
        setDecoration();
    }

    private void setDecoration() {
        result = AlbumBean.getClassifyAlbumBeanByVideoBean(videoBeanList);
        decorationBeanList = getDecorationBeanByAlbumBean(result);
        if (gridLayoutManager == null) {
            gridLayoutManager = new GridLayoutManager(getContext(), 3);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return AoniBeanDecorationUtils.getSpanSize(decorationBeanList, position);
                }
            });
            urgentRv.setLayoutManager(gridLayoutManager);
        }
        if (decoration != null) {
            urgentRv.removeItemDecoration(decoration);
        }
        decoration = new AlbumDecoration(decorationBeanList);
        urgentRv.addItemDecoration(decoration);
    }

    private List<AlbumDecoration.DecorationBean> getDecorationBeanByAlbumBean(List<AlbumBean> result) {
        List<AlbumDecoration.DecorationBean> temp = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            AlbumDecoration.DecorationBean d = new AlbumDecoration.DecorationBean(result.get(i).getPosition(), result.get(i).getDate(), result.get(i).getVideoBeanList().size());
            temp.add(d);
        }
        return temp;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LocalDeleteEvent event) {
        progressDialog.setMessage(getString(R.string.recorder_album_delete_file_hint));
        progressDialog.setCancelable(false);
        progressDialog.show();
                for (int i = 0; i < videoBeanList.size(); i++) {
                    if (videoBeanList.get(i).isCheck()) {
                        boolean b = new File(videoBeanList.get(i).getPath()).delete();
                        if (b) {
                            deleteBeans.add(videoBeanList.get(i));
                        }
                    }
                }
                if (deleteBeans.size() > 0) {
                    videoBeanList.removeAll(deleteBeans);
                    deleteBeans.clear();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateUI();
                            progressDialog.dismiss();
                            Toast.makeText(MyApplication.getInstance(), getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    progressDialog.dismiss();
                }


//            MediaScannerConnection.scanFile(getContext(), new String[]{deleteBeans.get(0).getPath()}, null, this);
    }

    @Override
    public void scanComplete(final Cursor cursor) {
        videoBeanList = getVideoBeanList(cursor);
        LogUtil.e("llcTest","--------111888---:"+videoBeanList.size());
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (urgentRv != null) {
                    updateUI();
                }
            }
        });

    }

    public int getVideoNum() {
        return videoBeanList == null ? 0 : videoBeanList.size();
    }

    public VideoBean getSelectedPhotoBean() {
        for (int i = 0; i < videoBeanList.size(); i++) {
            if (videoBeanList.get(i).isCheck()) {
                return videoBeanList.get(i);
            }
        }
        return null;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            EventBus.getDefault().unregister(this);
        } else {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (getUserVisibleHint() && resultCode == 200) {
            MediaScanner.scanVideos(DownLoadManager.URGENT_VIDEO_PATH, this);
        }
    }

    public List<VideoBean> getVideoBeanList(Cursor cursor) {
        List<VideoBean> videoBeanList = new ArrayList<>();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        while (cursor.moveToNext()) {
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            if (!new File(path).exists()){
                continue;
            }
            long time = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DATE_ADDED));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DURATION));
            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
            String tags = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TAGS));
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
            LogUtil.e("llcTest", "---1--------time-:" + time);
            LogUtil.e("llcTest", "---1--------duration-:" + duration);
            LogUtil.e("llcTest", "----1-------tags-:" + tags);
            LogUtil.e("llcTest", "----1-------name-:" + name);
            CarControl.CarDvThumbnailMediaInfo mediaInfo = CacheManager.getCarDvThumbnailMediaInfo(tags);
            String resolution;
            String fileTime;
            if (mediaInfo != null) {
                resolution = mediaInfo.resolution;
                fileTime = mediaInfo.file_time;
                if (!TextUtils.isEmpty(mediaInfo.file_time) && mediaInfo.file_time.contains(" ")) {
                    VideoBean v = new VideoBean(mediaInfo.file_time.split(" ")[0], path, name, resolution, fileTime, duration);
                    videoBeanList.add(v);
                }
            }
        }
        cursor.close();
        return videoBeanList;
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        videoBeanList.remove(deleteBeans.get(0));
        deleteBeans.remove(0);
        if (deleteBeans.size() > 0) {
            MediaScannerConnection.scanFile(getContext(), new String[]{deleteBeans.get(0).getPath()}, null, this);
        } else {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateUI();
                    progressDialog.dismiss();
                    Toast.makeText(MyApplication.getInstance(), getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

    @Override
    public void onItemLongClick(View view, int position, boolean isEditMode) {
        EventBus.getDefault().post(new LongClickEditEvent());
    }

    @Override
    public void onItemClick(CheckBox selectCb, int position, boolean isEditMode) {
        if (!isEditMode) {
            ActivityUtils.jumpActivityForResult(getActivity(), PlayVideoActivity.class, Constant.IntentKeyParam.POSITION, position, 10001);
            EventBus.getDefault().postSticky(new PlayVideoDataEvent(videoBeanList));
        } else {
            selectCb.setPressed(true);
            if (selectCb.isChecked()) {
                selectCb.setChecked(false);
            } else
                selectCb.setChecked(true);
            selectCb.setPressed(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        videoAdapter.unregisterEventBusForAdapter();
    }
}
